
# pages/dashboard.py - 仪表板页面
import streamlit as st
import pandas as pd
import numpy as np
import plotly.express as px
import plotly.graph_objects as go
from st_pages import add_page_title

# 检查认证状态
if 'authentication_status' not in st.session_state or not st.session_state.authentication_status:
    st.error("请先登录!")
    st.stop()

add_page_title()

# 生成示例数据
@st.cache_data
def generate_sample_data():
    """生成示例数据"""
    dates = pd.date_range(start='2024-01-01', end='2024-12-31', freq='D')
    data = {
        'date': dates,
        'sales': np.random.normal(1000, 200, len(dates)).cumsum(),
        'users': np.random.poisson(50, len(dates)).cumsum(),
        'revenue': np.random.normal(5000, 1000, len(dates)).cumsum()
    }
    return pd.DataFrame(data)

# 主要内容
st.markdown("### 📊 关键指标概览")

# KPI指标
df = generate_sample_data()
latest_data = df.iloc[-1]

col1, col2, col3, col4 = st.columns(4)

with col1:
    st.metric(
        label="总销售额",
        value=f"{latest_data['sales']:,.0f}",
        delta=f"{df.iloc[-1]['sales'] - df.iloc[-2]['sales']:+.0f}"
    )

with col2:
    st.metric(
        label="总用户数",
        value=f"{latest_data['users']:,.0f}",
        delta=f"{df.iloc[-1]['users'] - df.iloc[-2]['users']:+.0f}"
    )

with col3:
    st.metric(
        label="总收入",
        value=f"${latest_data['revenue']:,.0f}",
        delta=f"${df.iloc[-1]['revenue'] - df.iloc[-2]['revenue']:+.0f}"
    )

with col4:
    avg_order_value = latest_data['revenue'] / latest_data['users'] if latest_data['users'] > 0 else 0
    st.metric(
        label="平均订单价值",
        value=f"${avg_order_value:.2f}",
        delta=None
    )

st.divider()

# 图表展示
col1, col2 = st.columns(2)

with col1:
    st.subheader("📈 销售趋势")
    fig_sales = px.line(df.tail(30), x='date', y='sales', title="最近30天销售趋势")
    fig_sales.update_traces(line_color='#1f77b4')
    st.plotly_chart(fig_sales, use_container_width=True)

with col2:
    st.subheader("👥 用户增长")
    fig_users = px.area(df.tail(30), x='date', y='users', title="最近30天用户增长")
    fig_users.update_traces(fill='tonexty', fillcolor='rgba(31,119,180,0.3)')
    st.plotly_chart(fig_users, use_container_width=True)

# 收入分析
st.subheader("💰 收入分析")
fig_revenue = go.Figure()
fig_revenue.add_trace(go.Scatter(
    x=df['date'].tail(90),
    y=df['revenue'].tail(90),
    mode='lines',
    name='累计收入',
    line=dict(color='green', width=3)
))
fig_revenue.update_layout(title="最近90天收入趋势", xaxis_title="日期", yaxis_title="收入 ($)")
st.plotly_chart(fig_revenue, use_container_width=True)